package com.cloudDemoProduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cloudDemoProduct.dao.ProductQueryDao;
import com.cloudDemoProduct.service.ProductService;
import entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Daft_V
 * @date 2022/5/6 9:46
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductQueryDao productQueryDao;

    @Override
    public List<Product> productList() {
        return productQueryDao.list();
    }

    @Override
    public Product queryProductById(int id) {
        Product product = productQueryDao.getById(id);
        return product;
    }

    @Override
    public Boolean updateStock(int pid, int number) {
        Product product = productQueryDao.getById(pid);
        if (Objects.isNull(product)) {
            return false;
        }
        if (product.getStock() - number < 0 || number < 1) {
            return false;
        }
        try {
            UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
            productUpdateWrapper.eq("pid", pid);
            int num = product.getStock() - number;
            product.setStock(num);
            productQueryDao.getBaseMapper().update(product, productUpdateWrapper);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
